package com.wuwei.elearning.pdf;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.question.domain.AudioQuestion;
import com.wuwei.elearning.question.mapper.AudioQuestionMapper;
import lombok.SneakyThrows;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@SpringBootTest
public class PdfGetText {

    @SneakyThrows
    @Test
    public void getText(){
        String path = "D:\\BaiduNetdiskDownload\\四级听力原文 2016.06-2023.12.pdf";
        File file = new File(path);
        PDDocument document = PDDocument.load(file);
        PDFTextStripper pdfStripper = new PDFTextStripper();
        String specificPagesText = pdfStripper.getText(document);
        System.out.println(specificPagesText);
        String[] lines = specificPagesText.split("\n");


        StringBuilder stringBuilder = new StringBuilder();
        boolean findText = false;
        int i = 1;
        for (String line : lines) {
            int indexOf = line.indexOf("年");
            int length = line.length();
            if (indexOf==4&&line.substring(length-2,length-1).equals("套")) {
                //找到每套题原文的起点
                this.writeToSql(stringBuilder,i);
                i++;
                stringBuilder.setLength(0);
                stringBuilder.append(line);
                findText = true;
                continue;
            }
            if (findText&&line.indexOf("英语四级听力原文汇编")!=0) {
                stringBuilder.append(line);
            }
        }
    }

    @Resource
    private AudioQuestionMapper audioQuestionMapper;

    /**
     * 将字符串写入数据库
     * @param stringBuilder
     */
    private void writeToSql(StringBuilder stringBuilder,int i) {
        String s = stringBuilder.toString();
        if (!"".equals(s)) {
            String[] lines = s.split("\r");
            String title =  lines[0];
            List<Integer> nums =  this.getNums(title);
            String mouth = nums.get(1).toString().length()>1?nums.get(1).toString():"0"+nums.get(1).toString();
            String q_title = nums.get(0).toString()+"年"+mouth+"月四级听力音频第"+nums.get(2).toString()+"套";
            //把s存储到E盘audio目录下的text文件夹下，存储文件名命名为q_title
            // 定义文件路径和名称
            String directoryPath = "E:/audio/text";
            String filePath = directoryPath + "/" + q_title + ".txt";

            // 确保目录存在
            File directory = new File(directoryPath);
            if (!directory.exists()) {
                directory.mkdirs();  // 创建目录，包括任何必要但不存在的父目录
            }

            // 将字符串写入文件
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
                writer.write(s);
                System.out.println("File written successfully to " + filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 提取2023年 12月大学英语四级听力原文第1套这样一种字符串，提取其中的纯数字部分组成一个数组
     * @return
     */
    private List<Integer> getNums(String input) {
        //去除空格
        String result = input.chars()
                .filter(c -> !Character.isWhitespace(c))
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.joining());

        // 正则表达式匹配数字
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(result);

        // 存放数字的列表
        List<Integer> numbers = new ArrayList<>();

        // 提取数字并存入列表
        while (matcher.find()) {
            numbers.add(Integer.parseInt(matcher.group()));
        }
        return numbers;
    }
}

